package ee.greaton.siteManager.DB;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import ee.greaton.siteManager.model.Module;
import ee.greaton.siteManager.utils.Config;

public class ModuleHelper {
	public static String CMS_MODULE_DIR = Config.path;
	
	public static ArrayList<Module> getModuleList(Connection connection){
		ArrayList<Module> modules = new ArrayList<Module>();
		ResultSet rs = null;
		Statement statement = null;

		String query = "SELECT id, directory, name FROM cms_module WHERE admin = '0';";
		try {
			statement = connection.createStatement();
			rs = statement.executeQuery(query);

			while (rs.next()) {
				String dir = rs.getString("directory");
				if (new File(CMS_MODULE_DIR + dir).list() != null) {
					if (dir.indexOf("module") != -1) {
						modules.add(new Module(CMS_MODULE_DIR + dir, rs
								.getInt("id"), rs.getString("name")));
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return modules;
	}
}
